package server.storage;

import java.io.*;
import java.util.StringTokenizer;

public class LoginDataService {

    private DataOutputStream oos;

    public LoginDataService(String path) throws IOException {
        File file = new File(path);
        if(!file.exists()) {
            file.createNewFile();
        }
        oos = new DataOutputStream(new FileOutputStream(file,true));
    }

    public static String getPasswordByLogin (String path, String login) throws IOException {
        boolean find = false;
        String pairLoginPassword;
        String password = null;
        try(DataInputStream ois = new DataInputStream(new FileInputStream(new File(path)))) {
            while ((ois.available() > 0) && (!find)) {
                pairLoginPassword = ois.readUTF();
                StringTokenizer st = new StringTokenizer(pairLoginPassword, " ");
                if (login.equals(st.nextToken())) {
                    find = true;
                    password = st.nextToken();
                }
            }
        }
        if (find) {
            return password;
        } else {
            return null;
        }
    }

    public boolean addNewClient (String  login, String password){
        try {
            oos.writeUTF(login+" "+password);
            oos.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public void close () {
        try {
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
